package com.zw.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

public class AESUtil {

    // AES密钥长度（128/192/256位）
    private static final int KEY_SIZE = 256;
    // 加密算法模式
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

    /**
     * 生成AES密钥
     */
    /*public static String generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(KEY_SIZE);
        SecretKey secretKey = keyGen.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }
*/
    /**
     * AES加密
     * @param plainText 明文
     * @param base64Key Base64编码后的密钥
     * @return Base64编码的密文（包含IV）
     */
    public static String encrypt(String plainText, String base64Key) throws Exception {
        // 将Base64密钥转换为SecretKey
        byte[] keyBytes = Base64.getDecoder().decode(base64Key);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

        // 生成随机IV（16字节）
        byte[] ivBytes = new byte[16];
        SecureRandom random = new SecureRandom();
        random.nextBytes(ivBytes);
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        // 加密
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

        // 拼接IV和密文，并Base64编码
        byte[] combined = new byte[ivBytes.length + encryptedBytes.length];
        System.arraycopy(ivBytes, 0, combined, 0, ivBytes.length);
        System.arraycopy(encryptedBytes, 0, combined, ivBytes.length, encryptedBytes.length);
        return Base64.getEncoder().encodeToString(combined);
    }

    /**
     * AES解密
     * @param encryptedText Base64编码的密文（包含IV）
     * @param base64Key Base64编码后的密钥
     * @return 明文
     */
    public static String decrypt(String encryptedText, String base64Key) throws Exception {
        // 将Base64密钥转换为SecretKey
        byte[] keyBytes = Base64.getDecoder().decode(base64Key);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

        // 解析密文和IV
        byte[] combined = Base64.getDecoder().decode(encryptedText);
        byte[] ivBytes = new byte[16];
        byte[] encryptedBytes = new byte[combined.length - ivBytes.length];
        System.arraycopy(combined, 0, ivBytes, 0, ivBytes.length);
        System.arraycopy(combined, ivBytes.length, encryptedBytes, 0, encryptedBytes.length);

        // 解密
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    // 测试代码
    public static void main(String[] args) throws Exception {
        // 生成密钥（需保存备用）
        String key = "6v3yE9Q8Vqk7zXwLpAeRr2tJmZcYfHhN";
        System.out.println("AES密钥（Base64）: " + key);

        // 加密示例
        String plainText = "Hello，需要加密的敏感数据123！";
        String encrypted = encrypt(plainText, key);
        System.out.println("加密结果: " + encrypted);

        // 解密示例
        String decrypted = decrypt("5uO2yHuRZ2GjZu+OJ+FAbUkOq70E6AygvltNTt2AZF5eZ3RH3+wGRXofxG1DvEnN", key);
        System.out.println("解密结果: " + decrypted);
    }
}
